package com.chookss.mine.set;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.WebCommonActivity;
import com.chookss.base.StaticClass;
import com.chookss.base.Token;
import com.chookss.home.other.WxBindActivity;
import com.chookss.home.update.InstallLocalApk;
import com.chookss.login.LoginActivity;
import com.chookss.tools.CacheUtils;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.view.listener.ShareDialogListener;
import com.chookss.view.UpdateDialog;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.lvgroup.hospital.base.BaseAct;
import com.meituan.android.walle.WalleChannelReader;

import org.jetbrains.annotations.Nullable;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;

public class SettingActivity extends BaseAct {
    @BindView(R.id.common_title_txt)
    TextView common_title_txt;
    @BindView(R.id.tvQuit)
    TextView tvQuit;
    @BindView(R.id.tvNew)
    TextView tvNew;
    @BindView(R.id.tvCache)
    TextView tvCache;
    @BindView(R.id.tvBindTitle)
    TextView tvBindTitle;
    @BindView(R.id.tvBind)
    TextView tvBind;
    @BindView(R.id.llBind)
    LinearLayout llBind;
    @BindView(R.id.rl_my_change)
    RelativeLayout rl_my_change;
    @BindView(R.id.rl_my_logout)
    RelativeLayout rl_my_logout;
    @BindView(R.id.tvQuitChange)
    TextView tvQuitChange;
    private String fileUrl = "", versionName, versionDesc, updateFlag, fileName;
    private String url;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        common_title_txt.setText("设置");
        try {
            tvCache.setText(CacheUtils.getTotalCacheSize(this));
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(getPackageName().equals("com.zhaofengnum")){
            rl_my_change.setVisibility(View.GONE);
        }
        tvQuit.setVisibility(View.VISIBLE);
        String channel=WalleChannelReader.getChannel(this);
//        if(!Utils.isNull(channel)){
//            if(channel.contains("360")){
                rl_my_logout.setVisibility(View.VISIBLE);
//            }
//        }
        registerBoradcastReceiver();
        getVersion();
//        tvQuit.setVisibility(View.GONE);
//        tvQuitChange.setVisibility(View.VISIBLE);
//        url = new ShareUtils().getString(SettingActivity.this,
//                StaticClass.BASE_ADDRESS, "http://117.158.4.243:38006/dev_kmer/");
//        if (url.contains("dev_kmer")) {
//            tvQuitChange.setText("退出登录后杀死APP切换到生产环境");
//        } else {
//            tvQuitChange.setText("退出登录后杀死APP切换到测试环境");
//        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        getMyWorkList();
    }

    public void getMyWorkList() {
        //获取代办信息
        MyHttpRequest.getDefault().getRequestCompat(null, Urls.homepageMyWorkList, SignUtils2.makeSignStr(null), false, new ObserverCallback<String>() {
            @Override
            public void onSuccess(String data) {
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    if ("200".equals(jsonObject.getString("code"))) {
                        JSONObject jsonObject1 = jsonObject.getJSONObject("data");
                        int bindInt = Utils.changeNumber(jsonObject1.getString("bindingWx"));
                        if (bindInt > 0) {
                            llBind.setVisibility(View.VISIBLE);
                            tvBindTitle.setText("绑定"+getResources().getText(R.string.app_name)+"公众号");
                            new ShareUtils().putBoolean(SettingActivity.this, StaticClass.BIND_WX, false);
                        } else {
                            llBind.setVisibility(View.INVISIBLE);
                            tvBindTitle.setText("已绑定"+getResources().getText(R.string.app_name)+"公众号");
                            new ShareUtils().putBoolean(SettingActivity.this, StaticClass.BIND_WX, true);
                            new ShareUtils().putLong(SettingActivity.this, StaticClass.EMPLOYEECODE + "-" + StaticClass.BIND_WX_TIME, 0);

                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(String errorMsg) {
            }
        });
    }

    /**
     * @param isChange true表示开启切换环境模式
     */
    private void quit(boolean isChange) {
        MyHttpRequest.getDefault().postRequestCompat(null, Urls.logout, null, false,
                new ObserverCallback<String>() {
                    @Override
                    public void onSuccess(String data) throws Exception {
                        JSONObject reObject = new JSONObject(data);
                        KLog.i(data);
                        dismissLoading();
                        //清空账号信息
//                        List<AccountEntity> list = XJson.getAccountsList(SettingActivity.this, new ShareUtils().getString(SettingActivity.this, StaticClass.APPACCOUNT, ""), AccountEntity.class);
//                        list.clear();
//                        XJson.setAccountsList(SettingActivity.this, new ShareUtils().getString(SettingActivity.this, StaticClass.APPACCOUNT, ""), list);
                        if ("200".equals(reObject.getString("code"))) {
                            if (isChange) {
                                if (url.contains("dev_kmer")) {
                                    new ShareUtils().putString(SettingActivity.this,
                                            StaticClass.BASE_ADDRESS, "http://117.158.4.243:38006/kmer/");
                                    MyToast.show("杀死APP重新登录切换到生产环境");
                                } else {
                                    new ShareUtils().putString(SettingActivity.this,
                                            StaticClass.BASE_ADDRESS, "http://117.158.4" +
                                                    ".243:38012/dev_kmer/");
                                    MyToast.show("杀死APP重新登录切换到测试环境");
                                }
                            } else {
                                MyToast.show(reObject.getString("msg"));
                            }
                            Token.INSTANCE.quit();
                            new ShareUtils().putString(SettingActivity.this, "token", "");
                            new ShareUtils().putString(SettingActivity.this, StaticClass.USERNAME, "");
                            new ShareUtils().putString(SettingActivity.this, StaticClass.ORIGINALPASS, "");
                            new ShareUtils().putString(SettingActivity.this, StaticClass.EMPLOYEECODE, "");
                            new ShareUtils().putString(SettingActivity.this, StaticClass.COMPANYNAME, "");
                            new ShareUtils().putString(SettingActivity.this, StaticClass.COMPANYCODE, "");
                            Intent intent = new Intent(SettingActivity.this, LoginActivity.class);
                            startActivity(intent);
                            finish();
                        } else {
                            MyToast.show(reObject.getString("msg"));

                        }


                    }

                    @Override
                    public void onError(String errorMsg) {
                        MyToast.show(Utils.onErrorTips(errorMsg));
                        dismissLoading();
                    }
                });
    }

    public void unbindPUSHID() {
        //解绑设备id
        showLoading();
        Map<String, String> map = new HashMap<>();
        map.put("employeeCode", new ShareUtils().getString(SettingActivity.this, StaticClass.EMPLOYEECODE, ""));
        map.put("companyCode", new ShareUtils().getString(SettingActivity.this, StaticClass.COMPANYCODE, ""));
        MyHttpRequest.getDefault().getRequestCompat(null, Urls.unbindPUSHID, SignUtils2.makeSignStr(map), false, new ObserverCallback<String>() {
            @Override
            public void onSuccess(String data) {
                JSONObject reObject = null;
                try {
                    reObject = new JSONObject(data);
                    if ("200".equals(reObject.getString("code"))) {
                        Intent intent = new Intent();
                        intent.setAction(StaticClass.ACCOUNT_OUT);
                        LocalBroadcastManager.getInstance(SettingActivity.this).sendBroadcast(intent);
                        quit(false);

                    } else {
                        MyToast.show(reObject.getString("msg"));
                        dismissLoading();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    dismissLoading();
                }
            }

            @Override
            public void onError(String errorMsg) {
            }
        });
    }

    public void getVersion() {
        //获取版本号
        Map<String, String> map = new HashMap<>();
        map.put("system", "0");
        if (getPackageName().equals("com.zhaofengnum")) {
            map.put("downloadAddress", "zhaofeng");
        }
        MyHttpRequest.getDefault().getRequestCompat(null, Urls.getVersion, SignUtils2.makeSignStr(map), false, new ObserverCallback<String>() {
            @Override
            public void onSuccess(String data) {
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    if ("200".equals(jsonObject.getString("code"))) {
                        JSONObject jsonObject1 = jsonObject.getJSONObject("data");
                        int versionCode = Utils.changeNumber(jsonObject1.getString("versionCode"));
                        if (versionCode > Utils.getVersionCode(SettingActivity.this)) {
                            tvNew.setVisibility(View.VISIBLE);
                            fileUrl = jsonObject1.getString("downloadAddress");
                            versionName = jsonObject1.getString("versionName");
                            versionDesc = jsonObject1.getString("versionDesc");
                            updateFlag = jsonObject1.getString("updateFlag");
                            fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(String errorMsg) {
            }
        });
    }

    private final int GET_UNKNOWN_APP_SOURCES = 0x101;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @androidx.annotation.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case GET_UNKNOWN_APP_SOURCES:
                // 用户授予了未知来源应用的权限
                if (resultCode == RESULT_OK) {
                    InstallLocalApk.install(SettingActivity.this, new File(getExternalFilesDir(Urls.APKFOLDER), fileName));
                }
                break;
        }
    }

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null) {
                int percent = intent.getIntExtra("percent", 0);
                if (percent == 100) {
                    // 如果是8.0系统
                    if (Build.VERSION.SDK_INT >= 30) {
                        InstallLocalApk.install(SettingActivity.this, new File(getExternalFilesDir(Urls.APKFOLDER), fileName));
                    } else if (Build.VERSION.SDK_INT >= 26) {
                        boolean b = getPackageManager().canRequestPackageInstalls();
                        // 如果已经打开了安装未知来源的开关
                        if (b) {
                            InstallLocalApk.install(SettingActivity.this, new File(getExternalFilesDir(Urls.APKFOLDER), fileName));
                        } else {
                            // 请求打开安装未知应用来源的界面,非运行时权限
                            Uri packageURI = Uri.parse("package:" + getPackageName());
                            Intent intents = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
                            startActivityForResult(intents, GET_UNKNOWN_APP_SOURCES);
                        }
                    } else {
                        InstallLocalApk.install(SettingActivity.this, new File(getExternalFilesDir(Urls.APKFOLDER), fileName));
                    }
                }
            }
        }

    };

    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction("downApk");// 获取数据
        LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mBroadcastReceiver != null && this != null) {
            LocalBroadcastManager.getInstance(this).unregisterReceiver(mBroadcastReceiver);
        }
    }

    @OnClick({R.id.common_title_back, R.id.rl_my_logout, R.id.rlPrivacy, R.id.rlSecurity, R.id.rlNoticeSetting, R.id.rlUserAgreement,
            R.id.rlAboutUs, R.id.rlUpdate, R.id.rl_my_bind, R.id.rl_my_cache, R.id.rl_my_change, R.id.tvQuit, R.id.tvQuitChange})
    public void onClick(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
                break;
            case R.id.rl_my_logout:
                //注销
                intent = new Intent(this, LogoutActivity.class);
                startActivity(intent);
                break;
            case R.id.rlSecurity:
                intent = new Intent(this, AccountSecurityActivity.class);
                startActivity(intent);
                break;
            case R.id.rlNoticeSetting:
                intent = new Intent(this, NoticeSettingActivity.class);
                startActivity(intent);
                break;
            case R.id.rlUserAgreement:
                intent = new Intent(this, WebCommonActivity.class);
                intent.putExtra("title", "用户协议");
                if(getPackageName().equals("com.zhaofengnum")){
                    intent.putExtra("url", "http://dev.zhongyuanliantuo.com:38012/zhaofeng_license.html");
                }else{
                    intent.putExtra("url", Urls.license);
                }
                startActivity(intent);
                break;
            case R.id.rlPrivacy:
                intent = new Intent(this, WebCommonActivity.class);
                intent.putExtra("title", "隐私政策");;
                if(getPackageName().equals("com.zhaofengnum")){
                    intent.putExtra("url", "file:///android_asset/zhaofeng_privacy.html");
                }else{
                    intent.putExtra("url", "file:///android_asset/chookss_privacy.html");
                }
                startActivity(intent);
                break;
            case R.id.rlAboutUs:
                intent = new Intent(this, AboutActivity.class);
                startActivity(intent);
                break;
            case R.id.rlUpdate:
                if (MyApp.isDownApk) {
                    MyToast.show("新版本下载中");
                    return;
                }
                if (!Utils.isNull(fileUrl)) {
                    new UpdateDialog(this, versionName, versionDesc, updateFlag, fileUrl, new ShareDialogListener() {
                        @Override
                        public void onClick() {
                            // 如果是8.0系统
                            if (Build.VERSION.SDK_INT >= 30) {
                                InstallLocalApk.install(SettingActivity.this, new File(getExternalFilesDir(Urls.APKFOLDER), fileName));
                            } else if (Build.VERSION.SDK_INT >= 26) {
                                boolean b = getPackageManager().canRequestPackageInstalls();
                                // 如果已经打开了安装未知来源的开关
                                if (b) {
                                    InstallLocalApk.install(SettingActivity.this, new File(getExternalFilesDir(Urls.APKFOLDER), fileName));
                                } else {
                                    // 请求打开安装未知应用来源的界面,非运行时权限
                                    Uri packageURI = Uri.parse("package:" + getPackageName());
                                    Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
                                    startActivityForResult(intent, GET_UNKNOWN_APP_SOURCES);
                                }
                            } else {
                                InstallLocalApk.install(SettingActivity.this, new File(getExternalFilesDir(Urls.APKFOLDER), fileName));
                            }
                        }
                    }).show();
                } else {
                    MyToast.show("已经是最新版本了");
                }
                break;
            case R.id.rl_my_cache:
                showLoading();
                CacheUtils.clearAllCache(this);
                //定时器 倒计时
                Observable.timer(600, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Consumer<Long>() {
                            @Override
                            public void accept(Long aLong) {
                                dismissLoading();
                                MyToast.show("清除完成");
                                tvCache.setText("0M");
                            }
                        });
                break;
            case R.id.rl_my_bind:
                //绑定公众号
                if (!tvBindTitle.getText().toString().contains("已绑定")) {
                    intent = new Intent(this, WxBindActivity.class);
                    intent.putExtra("url", Urls.bing_wx);
                    intent.putExtra("title", "我的绑定");
                    startActivity(intent);
                }
                break;
            case R.id.rl_my_change:
                //切换所属组织
                intent = new Intent(this, AccountActivity.class);
                startActivity(intent);
                break;
            case R.id.tvQuit:
                unbindPUSHID();
                break;
            case R.id.tvQuitChange:
                unbindPUSHID();
//                quit(true);
                break;
        }
    }
}
